package com.lijian.study.mongo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.lijian.study.mongo.Entity.Address;
import com.lijian.study.mongo.Entity.Role;
import com.lijian.study.mongo.Entity.User;
import com.lijian.study.mongo.repository.UserRepository;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    // 获取所有用户
    public List<User> findAll() {
        return userRepository.findAll();
    }

    // 保存用户
    public User save(User user) {
        return userRepository.save(user);
    }

    // 根据 ID 查找用户
    public User findById(String id) {
        return userRepository.findById(id).orElse(null);
    }

    // 根据 ID 删除用户
    public void deleteById(String id) {
        userRepository.deleteById(id);
    }

    // 添加地址
    public User addAddress(String userId, Address address) {
        User user = findById(userId);
        if (user != null) {
            user.getAddresses().add(address);
            return userRepository.save(user);
        }
        return null;
    }

    // 添加角色
    public User addRole(String userId, Role role) {
        User user = findById(userId);
        if (user != null) {
            user.getRoles().add(role);
            return userRepository.save(user);
        }
        return null;
    }

    // 使用Criteria API进行复杂查询
    @Autowired
    private MongoTemplate mongoTemplate;

    public List<User> findUsersByComplexCriteria(String name, String email, LocalDateTime startDate,
            LocalDateTime endDate) {
        Query query = new Query();
        // 添加姓名条件
        if (name != null) {
            query.addCriteria(Criteria.where("name").is(name));
        }
        // 添加电子邮件条件
        if (email != null) {
            query.addCriteria(Criteria.where("email").is(email));
        }
        // 添加创建日期范围条件
        if (startDate != null && endDate != null) {
            query.addCriteria(Criteria.where("createdDate").gte(startDate).lte(endDate));
        }
        return mongoTemplate.find(query, User.class);
    }

    // 使用Aggregation进行更复杂的数据处理和分析

    public List<User> aggregateUserRoles() {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("roles").exists(true)), // 匹配有角色的用户
                Aggregation.group("roles").count().as("totalUsers") // 按角色分组并统计用户数量
        );

        AggregationResults<User> results = mongoTemplate.aggregate(aggregation, User.class, User.class);
        return results.getMappedResults();
    }
}
